<?php

namespace App\Console\Commands;

use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;

class EnterpriseRecharge extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'enterprise_recharge';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
		while (true){

			foreach($this->getItem() as $v){
				if (!$v){
					continue;
				}
				try{
					$user = User::where('id',$v->relation_id)->first();
					if (!$user){
						continue;
					}
					\DB::beginTransaction();
					$user->increment('currentCommission', $v->money);
					$user->increment('rewards_all', $v->money);
					$user->save();
					\DB::table("enterprise_recharge_fenxiao_queue")->where('id', $v->id)->update(['status'=>1]);
					switch ($v->relation){
						//业务员
						case 1:
							\DB::table("user_salesman_bonus_count")->insert([
								'type'=>3,
								'income_type'=>1,
								'user_id'=>$v->relation_id,
								'money'=>$v->money,
								'relation_id'=>$v->id,
								'describe'=>'企业开通年费佣金',
								'created_at'=>Carbon::now()
							]);
							break;
						//运营商
						case 2:
							\DB::table("user_operators_bonus_count")->insert([
								'type'=>2,
								'income_type'=>1,
								'user_id'=>$v->relation_id,
								'money'=>$v->money,
								'relation_id'=>$v->id,
								'describe'=>'企业开通年费佣金',
								'created_at'=>Carbon::now()
							]);
							break;
						//城市合伙人
						case 3:
							\DB::table("user_place_partner_bonus_count")->insert([
								'type'=>3,
								'income_type'=>1,
								'user_id'=>$v->relation_id,
								'money'=>$v->money,
								'relation_id'=>$v->id,
								'describe'=>'企业开通年费佣金',
								'created_at'=>Carbon::now()
							]);
							break;
					}

					\DB::commit();
					sleep(5);
				}catch (\Exception $e){
					\DB::rollBack();
					sleep(5);
				}
			}
			sleep(10);
		}
    }
    private function getItem()
	{
		$result = \DB::table("enterprise_recharge_fenxiao_queue")->where('status', '0')->get();
		foreach($result as $v){
			yield $v;
		}
	}
}
